<template>
  <div class="p-2">
    <!-- 物模型协议管理 - 协议管理 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <el-form-item label="产品名称" prop="productName">
          <el-select v-model="queryParams.productName" placeholder="请选择产品名称" clearable style="width: 200px">
            <el-option label="全部" value="" />
            <el-option v-for="product in productList" :key="product.id" :label="product.name" :value="product.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="协议版本号" prop="protocolVersion">
          <el-input v-model="queryParams.protocolVersion" placeholder="请输入协议版本号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="通信协议类型" prop="communicationType">
          <el-select v-model="queryParams.communicationType" placeholder="请选择通信协议类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="HTTP" value="HTTP" />
            <el-option label="MQTT" value="MQTT" />
            <el-option label="TCP" value="TCP" />
            <el-option label="UDP" value="UDP" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增协议</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" :data="protocolList" @selection-change="handleSelectionChange" border fixed>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="通信协议ID" prop="protocolId" width="120" align="center" />
        <el-table-column label="协议名称" prop="protocolName" width="150" align="center" />
        <el-table-column label="产品名称" prop="productName" width="150" align="center" />
        <el-table-column label="协议版本号" prop="protocolVersion" width="120" align="center" />
        <el-table-column label="通信协议类型" prop="communicationType" width="140" align="center">
          <template #default="{ row }">
            <el-tag :type="getCommunicationTypeTagStyle(row.communicationType)">
              {{ getCommunicationTypeLabel(row.communicationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="编码格式" prop="encoding" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="info">{{ row.encoding || 'UTF-8' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === '1' ? 'success' : 'danger'">
              {{ row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" icon="Setting" @click="handleDataFormat(scope.row)">数据格式定义</el-button>
            <el-button link type="success" icon="Upload" @click="handlePublish(scope.row)">发布</el-button>

            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 协议表单弹窗 -->
    <ProtocolFormDialog v-model="formDialogVisible" :title="formDialogTitle" :protocol-data="currentProtocolData"
      @success="handleFormSuccess" />


  </div>
</template>

<script setup lang="ts" name="ProtocolList">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { Search, Refresh, Plus, Delete, Download, View } from '@element-plus/icons-vue'
import ProtocolFormDialog from './components/ProtocolFormDialog.vue'

// 移除远程API相关导入，改为本地虚拟数据
import type { ProtocolInfo, ProtocolQueryParams } from '@/api/IOT/protocolManage/protocolList/types'
import type { ProductInfo } from '@/api/IOT/protocolManage/productManage/types'

// 路由
const router = useRouter()

// 产品信息
const productInfo = reactive({
  id: '',
  name: '',
  categoryId: '',
  categoryName: ''
})

// 响应式数据
const loading = ref(false)
const tableData = ref<ProtocolInfo[]>([])
const total = ref(0)
const multipleSelection = ref<ProtocolInfo[]>([])
const protocolList = ref([])
const productList = ref<ProductInfo[]>([])

// 弹窗相关
const formDialogVisible = ref(false)
const formDialogTitle = ref('新增协议')
const currentProtocolData = ref<ProtocolInfo | null>(null)

// 查询参数
const queryParams = reactive<ProtocolQueryParams>({
  pageNum: 1,
  pageSize: 10,
  productName: '',
  protocolVersion: '',
  protocolVersionName: '',
  communicationType: ''
})

// 表单数据
const form = reactive({
  communicationProtocolId: '',
  productName: '',
  protocolVersion: '',
  protocolVersionName: '',
  status: '1',
  communicationType: ''
})

// 表单验证规则
const rules = reactive({
  productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  protocolVersion: [{ required: true, message: '协议版本号不能为空', trigger: 'blur' }],
  protocolVersionName: [{ required: true, message: '协议版本名不能为空', trigger: 'blur' }],
  communicationType: [{ required: true, message: '通信协议类型不能为空', trigger: 'change' }]
})

// 获取通信协议类型标签样式
const getCommunicationTypeTagStyle = (type: string) => {
  const styleMap: Record<string, string> = {
    HTTP: 'success',
    MQTT: 'warning',
    TCP: 'info',
    UDP: 'primary'
  }
  return styleMap[type] || 'info'
}

// 获取通信协议类型标签文本
const getCommunicationTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    HTTP: 'HTTP',
    MQTT: 'MQTT',
    TCP: 'TCP',
    UDP: 'UDP'
  }
  return labelMap[type] || type
}

// 获取传输协议标签样式
const getTransportTag = (transport: string) => {
  switch (transport) {
    case 'HTTP': return 'success'
    case 'MQTT': return 'warning'
    case 'TCP': return 'danger'
    case 'UDP': return 'info'
    default: return 'primary'
  }
}

// 获取数据格式标签样式
const getDataFormatTag = (format: string) => {
  switch (format) {
    case 'json': return 'success'
    case 'xml': return 'warning'
    case 'binary': return 'danger'
    case 'text': return 'info'
    case 'custom': return 'primary'
    default: return 'primary'
  }
}

// 获取数据格式文本
const getDataFormatText = (format: string) => {
  switch (format) {
    case 'json': return 'JSON'
    case 'xml': return 'XML'
    case 'binary': return '二进制'
    case 'text': return '文本'
    case 'custom': return '自定义'
    default: return '未知'
  }
}

// 本地虚拟延迟（随机不超过1.5s）
const delayRandom = (min = 300, max = 1500) => new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// 本地协议数据源
const allProtocols = ref<ProtocolInfo[]>([])

// 初始化本地协议数据
const initProtocols = () => {
  if (allProtocols.value.length) return
  const products = ['水质监测设备', '泵站控制器', '压力传感器', '流量计']
  const types = ['HTTP', 'MQTT', 'TCP', 'UDP']
  const encodings = ['UTF-8', 'GBK', 'ASCII', 'Unicode']
  const remarks = ['—', '用于水厂数据采集', '工业现场监控', '远程控制专用']
  const list: ProtocolInfo[] = []
  for (let i = 1; i <= 36; i++) {
    const productName = products[i % products.length]
    const communicationType = types[i % types.length]
    const encoding = encodings[i % encodings.length]
    list.push({
      protocolId: `PROTO-${String(i).padStart(3, '0')}`,
      protocolName: `通用协议-${i}`,
      productName,
      protocolVersion: `1.${i % 5}.${i % 10}`,
      communicationType,
      encoding,
      status: i % 3 === 0 ? '0' : '1',
      remark: remarks[i % remarks.length]
    } as any)
  }
  allProtocols.value = list
}

initProtocols()

// 查询协议列表（本地虚拟请求）
const getList = async () => {
  try {
    loading.value = true
    await delayRandom()
    // 过滤
    let filtered = [...allProtocols.value]
    if (queryParams.productName) {
      filtered = filtered.filter(p => p.productName === queryParams.productName)
    }
    if (queryParams.protocolVersion) {
      filtered = filtered.filter(p => p.protocolVersion.includes(queryParams.protocolVersion))
    }
    if (queryParams.communicationType) {
      filtered = filtered.filter(p => p.communicationType === queryParams.communicationType)
    }
    if ((queryParams as any).status) {
      filtered = filtered.filter(p => p.status === (queryParams as any).status)
    }
    // 分页
    const start = (queryParams.pageNum - 1) * queryParams.pageSize
    const end = start + queryParams.pageSize
    protocolList.value = filtered.slice(start, end)
    total.value = filtered.length
  } catch (error) {
    console.error('获取协议列表失败:', error)
    ElMessage.error('获取协议列表失败')
  } finally {
    loading.value = false
  }
}

// 删除按钮操作（本地虚拟请求）
const handleDelete = async (row?: ProtocolInfo) => {
  const protocolsToDelete = row ? [row] : multipleSelection.value
  if (protocolsToDelete.length === 0) {
    ElMessage.warning('请选择要删除的协议')
    return
  }

  const protocolNames = protocolsToDelete.map(item => item.protocolName).join('、')

  try {
    await ElMessageBox.confirm(
      `是否确认删除协议"${protocolNames}"？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    await delayRandom()
    const ids = new Set(protocolsToDelete.map(item => item.protocolId))
    allProtocols.value = allProtocols.value.filter(item => !ids.has(item.protocolId))
    multipleSelection.value = []
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 导出按钮操作（本地虚拟请求）
const handleExport = async () => {
  const downloadLoadingInstance = ElLoading.service({ text: '正在导出数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' })
  try {
    await delayRandom()
    const data = multipleSelection.value.length > 0 ? multipleSelection.value : protocolList.value
    // 生成CSV
    const header = ['通信协议ID','协议名称','产品名称','协议版本号','通信协议类型','编码格式','状态','备注']
    const rows = data.map(p => [p.protocolId, p.protocolName, p.productName, p.protocolVersion, p.communicationType, p.encoding || 'UTF-8', p.status === '1' ? '启用' : '禁用', p.remark || ''])
    const csv = [header.join(','), ...rows.map(r => r.map(v => `"${String(v).replace(/"/g, '""')}"`).join(','))].join('\n')
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `协议列表_${Date.now()}.csv`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    downloadLoadingInstance.close()
  }
}

// 弹窗事件处理（本地新增/修改）
const handleFormSuccess = (payload: any) => {
  const isEdit = !!payload.protocolId
  if (isEdit) {
    const idx = allProtocols.value.findIndex(p => p.protocolId === payload.protocolId)
    if (idx !== -1) {
      allProtocols.value[idx] = { ...allProtocols.value[idx], ...payload }
    }
  } else {
    const newId = `PROTO-${String(Math.max(0, ...allProtocols.value.map(p => parseInt((p.protocolId||'').split('-')[1] || '0'))) + 1).padStart(3, '0')}`
    allProtocols.value.unshift({
      protocolId: newId,
      protocolName: payload.protocolName,
      productName: payload.productName,
      protocolVersion: payload.protocolVersion,
      communicationType: payload.communicationType,
      encoding: payload.encoding,
      status: payload.status,
      remark: payload.remark
    } as any)
  }
  getList()
}

// 获取产品列表（本地写死 + 虚拟请求）
const getProductListData = async () => {
  try {
    await delayRandom()
    productList.value = [
      { id: 'P-1001', name: '水质监测设备' } as ProductInfo,
      { id: 'P-1002', name: '泵站控制器' } as ProductInfo,
      { id: 'P-1003', name: '压力传感器' } as ProductInfo,
      { id: 'P-1004', name: '流量计' } as ProductInfo
    ]
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  }
}

// 状态切换
const handleStatusChange = (row: any) => {
  const text = row.status === '1' ? '启用' : '禁用'
  ElMessageBox.confirm('确认要"' + text + '""' + row.protocolName + '"协议吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(text + '成功')
  }).catch(() => {
    row.status = row.status === '1' ? '0' : '1'
  })
}

// 新增按钮操作
const handleAdd = () => {
  formDialogTitle.value = '新增协议'
  currentProtocolData.value = null
  formDialogVisible.value = true
}

const multiple = ref(true)

// 编辑协议
const handleEdit = (row: ProtocolInfo) => {
  formDialogTitle.value = '修改协议'
  currentProtocolData.value = row
  formDialogVisible.value = true
}



// 查看关联产品
const viewProducts = (row: any) => {
  ElMessage.info('跳转到产品列表页面：' + row.protocolName)
}

// 发布协议
const handlePublish = (row: any) => {
  ElMessage.info('发布协议功能开发中：' + row.protocolName)
}

// 数据格式管理
const handleDataFormat = (row: any) => {
  // 跳转到数据格式管理页面，传递协议信息
  // 统一使用路由模块中的实际路径
  router.push({
    path: '/iot/protocol/data-format',
    query: {
      protocolId: row.protocolId,
      protocolName: row.protocolName
    }
  })
}





// 返回产品管理
const goBackToProduct = () => {
  router.push({
    path: '/iot/protocolManage/productManage',
    query: {
      categoryId: productInfo.categoryId,
      categoryName: productInfo.categoryName
    }
  })
}



// 组件挂载
onMounted(() => {
  const route = useRoute()
  // 获取路由参数
  if (route.query.productId) {
    productInfo.id = route.query.productId as string
  }
  if (route.query.productName) {
    productInfo.name = route.query.productName as string
  }
  // 保存品类信息用于返回
  if (route.query.categoryId) {
    productInfo.categoryId = route.query.categoryId as string
  }
  if (route.query.categoryName) {
    productInfo.categoryName = route.query.categoryName as string
  }
  getProductListData()
  getList()
})

const handleSelectionChange = (selection: ProtocolInfo[]) => {
  multipleSelection.value = selection
  multiple.value = selection.length === 0
}
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}
const resetQuery = () => {
  queryParams.productName = ''
  queryParams.protocolVersion = ''
  queryParams.communicationType = ''
  ;(queryParams as any).status = ''
  handleQuery()
}
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.protocol-icon {
  display: flex;
  justify-content: center;
  align-items: center;
}

.icon-uploader .icon {
  width: 60px;
  height: 60px;
  display: block;
  border-radius: 4px;
}

.icon-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.icon-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.icon-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
}
</style>